import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:sleep/model/blue/blue_model.dart';
import 'package:sleep/model/blue_connection_state.dart';
import 'package:sleep/page/blue/connect_item.dart';
import 'package:sleep/page/blue/scan_item.dart';
import 'package:sleep/help_style.dart';
import 'package:sleep/provider/blue/blue_provider.dart';
import 'package:sleep/provider/blue/blue_scaner.dart';
import 'package:sleep/provider/db_provider.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_reactive_ble/flutter_reactive_ble.dart';

class BlueScanScreen extends ConsumerWidget {
  @override
  Widget build(BuildContext context, ref) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        centerTitle: true,
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: Text("Scan", style: HelpStyle.titleStyle),
      ),
      body: blues(ref),
    );
  }

  mineWidget() {
    return Text(
      "我的设备",
      style: HelpStyle.contextStyle,
    );
  }

  Widget connetedBlue(BlueNotifier? notifier, DBNotifier db, BlueType type) {
    final device = notifier?.blue;
    return device == null
        ? Container(
            padding: const EdgeInsets.all(10),
            alignment: Alignment.center,
            child: Text(
              "暂无设备",
              style: HelpStyle.contextStyle,
            ),
          )
        : ConnectItem(
            blueId: device.deviceId,
            type: type,
            ontap: () {
              notifier?.connectBlue(device);
            },
            name: device.name,
            state: BlueConnectionState.disconnected,
            subChild: Row(
              children: [
                Text(
                  device.connectionState?.title ?? "",
                  style: HelpStyle.contextStyle,
                ),
                IconButton(
                    onPressed: () {
                      removeBlue(notifier!, db);
                    },
                    icon: Icon(
                      Icons.delete_outline_rounded,
                      color: HelpStyle.primarycolor,
                    ))
              ],
            ),
          );
  }

  loading() {
    return Row(
      children: [
        Text(
          "其他设备",
          style: HelpStyle.contextStyle,
        ),
        SizedBox(width: 12),
        CupertinoActivityIndicator(),
      ],
    );
  }

  blues(WidgetRef ref) {
    final scan = ref.watch(scanResultProvider);
    final db = ref.watch(dbProvider);
    final sleepBlue = ref.watch(sleepBlueProvider);
    final faigueBlue = ref.watch(faigueBlueProvider);
    final plueBlue = ref.watch(plueBlueProvider);

    return Padding(
      padding: const EdgeInsets.all(12.0),
      child: CustomScrollView(
        slivers: [
          SliverToBoxAdapter(
            child: mineWidget(),
          ),
          SliverToBoxAdapter(
            child: connetedBlue(sleepBlue, db, BlueType.sleep),
          ),
          SliverToBoxAdapter(
            child: connetedBlue(faigueBlue, db, BlueType.faigue),
          ),
          SliverToBoxAdapter(
            child: connetedBlue(plueBlue, db, BlueType.pulse),
          ),
          SliverToBoxAdapter(
            child: loading(),
          ),
          const SliverToBoxAdapter(
            child: SizedBox(height: 8),
          ),
          SliverList(
            delegate:
                SliverChildBuilderDelegate((BuildContext context, int index) {
              final device = scan[index];
              return ScanItem(
                blueId: device.deviceId,
                ontap: (type) {
                  final sleepBlue = ref.watch(sleepBlueProvider);
                  final faigueBlue = ref.watch(faigueBlueProvider);
                  final plueBlue = ref.watch(plueBlueProvider);
                  Map blueMap = {
                    BlueType.faigue: faigueBlue,
                    BlueType.pulse: plueBlue,
                    BlueType.sleep: sleepBlue,
                  };

                  saveAndconnect(blueMap[type], db, device);
                },
                name: device.name,
              );
            }, childCount: scan.length),
          ),
        ],
      ),
    );
  }

//event
  void saveAndconnect(
      BlueNotifier blueNotifier, DBNotifier db, BlueModel blue) {
    db.saveBlueModel(blue, blueNotifier.blueKey);
    blueNotifier.connectBlue(blue);
  }

  void connect() {}

  void removeBlue(BlueNotifier blueNotifier, DBNotifier db) {
    db.remove(blueNotifier.blueKey);
    blueNotifier.disConnectBlue();
  }
}
